//
//  RootViewController.m
//
//  上海杨浦
//
//  Created by FrankChen on 13-5-17.
//  Copyright (c) 2013年 FrankChen. All rights reserved.
//

#import "RootViewController.h"


#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) 
#define IOS_VERSION_7_OR_ABOVE (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)? (YES):(NO))


@interface RootViewController (Private) 


@end

@implementation RootViewController
@synthesize tableView = _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.arr_infoItem = [NSMutableArray array];
    
    // create the tableview
    int diff=0;
    if (iPhone5) {
        diff=diff+88;
    }
    if (IOS_VERSION_7_OR_ABOVE) {
        diff=diff+20;
    }
    if (IOS_VERSION_7_OR_ABOVE) {
        [self initTableViewWithRect:CGRectMake(self.view.bounds.origin.x,
                                               116+diff/1.7,
                                               self.view.frame.size.width,
                                               self.view.frame.size.height-165.0-diff/1.7)];
    }
    else{
        [self initTableViewWithRect:CGRectMake(self.view.bounds.origin.x,
                                               116+diff/1.7-20,
                                               self.view.frame.size.width,
                                               self.view.frame.size.height-165.0-diff/1.7)];
    }
    self.diff = diff;
}

-(void)initTableViewWithRect:(CGRect)aRect{
    _tableView = [[UITableView alloc] initWithFrame:aRect  style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //_tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    //[_tableView setSeparatorColor:[UIColor whiteColor]];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgImg_cell.png"]];
    [self.view addSubview: _tableView];
    [_tableView release]; 
}

#pragma mark
#pragma methods for creating and removing the header view

-(void)createHeaderView{
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
	_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:
                               CGRectMake(0.0f, 0.0f - self.view.bounds.size.height,
                                          self.view.frame.size.width, self.view.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    
	[_tableView addSubview:_refreshHeaderView];
    
    [_refreshHeaderView refreshLastUpdatedDate];
}

-(void)createHeaderView2{
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
	_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:
                          CGRectMake(0.0f, 0.0f - self.view.bounds.size.height,
                                     self.view.frame.size.width, self.view.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    
	[_tableView addSubview:_refreshHeaderView];
    
    [_refreshHeaderView refreshLastUpdatedDate];
}

-(void)removeHeaderView{
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
    _refreshHeaderView = nil;
}

-(void)setFooterView{
    //UIEdgeInsets test = _tableView.contentInset;
    // if the footerView is nil, then create it, reset the position of the footer
    CGFloat height = MAX(_tableView.contentSize.height, _tableView.frame.size.height);//控制footview
    //CGFloat height = _tableView.contentSize.height-44;
    if (_refreshFooterView && [_refreshFooterView superview]) {
        // reset position
        _refreshFooterView.frame = CGRectMake(0.0f, 
                                              height,
                                              _tableView.frame.size.width, 
                                              self.view.bounds.size.height);
    }else {
        // create the footerView
        _refreshFooterView = [[EGORefreshTableFooterView alloc] initWithFrame:
                               CGRectMake(0.0f, height,
                                          _tableView.frame.size.width, self.view.bounds.size.height)];
        _refreshFooterView.delegate = self;
        [_tableView addSubview:_refreshFooterView]; 
    }
    
    if (_refreshFooterView) {
        [_refreshFooterView refreshLastUpdatedDate];
    }
}

-(void)removeFooterView{
    if (_refreshFooterView && [_refreshFooterView superview]) {
        [_refreshFooterView removeFromSuperview];
    }
    _refreshFooterView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}

#pragma mark-
#pragma mark force to show the refresh headerView
-(void)showRefreshHeader:(BOOL)animated{
	if (animated)
	{
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		self.tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
        // scroll the table view to the top region
        [self.tableView scrollRectToVisible:CGRectMake(0, 0.0f, 1, 1) animated:NO];	
        [UIView commitAnimations];
	}
	else
	{
		self.tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[self.tableView scrollRectToVisible:CGRectMake(0, 0.0f, 1, 1) animated:NO];
	}
    
    [_refreshHeaderView setState:EGOOPullRefreshLoading];
}

#pragma mark -
#pragma mark overide UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
    }
    
	// Configure the cell.

    return cell;
}


#pragma mark -
#pragma mark data reloading methods that must be overide by the subclass

-(void)beginToReloadData:(EGORefreshPos)aRefreshPos{
	
	//  should be calling your tableviews data source model to reload
	_reloading = YES;
    
	// overide, the actual loading data operation is done in the subclass
}

#pragma mark -
#pragma mark method that should be called when the refreshing is finished
- (void)finishReloadingData{
	
	//  model should call this when its done loading
	_reloading = NO;
    
	if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_tableView];
    }
    
    if (_refreshFooterView) {
        [_refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:_tableView];
        [self setFooterView];
    }
    
    // overide, the actula reloading tableView operation and reseting position operation is done in the subclass
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
	
	if (_refreshFooterView) {
        [_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    }	
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
	
	if (_refreshFooterView) {
        [_refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}


#pragma mark -
#pragma mark EGORefreshTableDelegate Methods

- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos{
	
	[self beginToReloadData:aRefreshPos];
	
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}


// if we don't realize this method, it won't display the refresh timestamp
- (NSDate*)egoRefreshTableDataSourceLastUpdated:(UIView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}



#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    SAFE_RELEASE(_refreshHeaderView);
    SAFE_RELEASE(_refreshFooterView);
}

- (void)dealloc {
    [super dealloc];
}


#pragma mark - KK methods

- (void)kk_didSelectedItemWithIndexPath:(NSIndexPath*)indexPath {
    
    KKInfoItem *item = [self.arr_infoItem objectAtIndex: indexPath.row];
    
    [KKWebServiceManager kk_getInfoDetailWithInfoId: item.kk_Infoid success:^(id response) {
        
        NSString *content= response;
        
        NSString *title=item.kk_title;
        
        UIView *view=[[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)]autorelease];
        view.backgroundColor=[UIColor clearColor];
        
        UIWebView *webView = [[UIWebView alloc] initWithFrame: CGRectMake(0, 117+self.diff/1.7, 320, 300+self.diff/1.7)];
        webView.backgroundColor = [UIColor whiteColor];
        webView.scrollView.backgroundColor = [UIColor whiteColor];
        webView.scalesPageToFit =YES;//自动对页面进行缩放以适应屏幕
        [webView loadHTMLString: content baseURL: nil];
        [view addSubview: webView];
        
//        UIScrollView *scrollView=[[[UIScrollView alloc]initWithFrame:CGRectMake(0, 117+self.diff/1.7, 320, 300+self.diff/1.7)]autorelease];
//        UIColor *color=[UIColor whiteColor];
//        scrollView.backgroundColor=color;
        
        UIFont *font=[UIFont fontWithName:@"FZHTJW--GB1-0" size:16.0f];
        CGSize size=CGSizeMake(300, 5000000);
        //HUD.progress=0.70f;
        UILabel *lbl_title=[[UILabel alloc] initWithFrame:CGRectZero];
        [lbl_title setNumberOfLines:0];
        NSDictionary * tdic=[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
        title=[title stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
        
        
        CGSize lblsize1;
        if (IOS_VERSION_7_OR_ABOVE) {
            lblsize1=[title boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:Nil].size;
            
        }
        else{
            lblsize1=[title sizeWithFont:font constrainedToSize:size];
        }
        
        lbl_title.backgroundColor=[UIColor colorWithRed:0.937 green:0.918 blue:0.906 alpha:1];
        lbl_title.textColor=[UIColor darkGrayColor];
        lbl_title.font=font;
        lbl_title.textAlignment=NSTextAlignmentCenter;
        
        
        lbl_title.text=title;
        lbl_title.frame=CGRectMake(10, -lblsize1.height, 300, lblsize1.height);
        
        CGSize lblsize;
        if (IOS_VERSION_7_OR_ABOVE) {
            lblsize=[content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:Nil].size;
            
        }
        else{
            lblsize=[content sizeWithFont:font constrainedToSize:size];
        }
        
        
        UILabel *lbl_content=[[UILabel alloc] initWithFrame:CGRectZero];
        [lbl_content setNumberOfLines:0];
        //lbl_content.frame=CGRectMake(0, 15, lblsize.width, lblsize.height+30);
        lbl_content.backgroundColor=[UIColor colorWithRed:0.937 green:0.918 blue:0.906 alpha:1];
        lbl_content.textColor=[UIColor darkGrayColor];
        lbl_content.font=font;
        
        lbl_content.textAlignment=NSTextAlignmentLeft;
        
        
        lbl_content.text=content;
        
        
        lbl_content.frame=CGRectMake(15, lblsize1.height+10, 300, lblsize.height);
        
//        [scrollView addSubview:lbl_title];
//        [scrollView addSubview:lbl_content];
//        
//        [scrollView setContentSize:CGSizeMake(320, lblsize.height+lblsize1.height+100)];
        [webView setBackgroundColor:[UIColor colorWithRed:0.937 green:0.918 blue:0.906 alpha:1]];
        
        [webView.scrollView addSubview: lbl_title];
        [webView.scrollView setContentInset: UIEdgeInsetsMake(CGRectGetHeight(lbl_title.bounds), 0, 20, 0)];
        
        [self test_AddBtn_back];
        
//        [view addSubview:scrollView];
        
        
        [view addSubview:self.btn_Back];
        
        self.view1=view;
        
        [self.HUD removeFromSuperview];
        [self.HUD release];
        
        
        [self.view.superview addSubview:view];
        
    } faile:^{
        
    }];
}

-(void)test_AddBtn_back{
    CGRect frame=CGRectMake(21, 87+self.diff/1.7, 72, 29);
    UIButton *btn_back=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn_back setTag:51];
    [btn_back setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
    btn_back.frame=frame;
    [btn_back addTarget:self action:@selector(test_Btn_back_Clicked) forControlEvents:UIControlEventTouchUpInside];
    //[[self view]addSubview:btn_back];
    self.btn_Back=btn_back;
}

-(void)test_Btn_back_Clicked{
    //UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"show" message:@"1" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    //[alert show];
    [_view1 removeFromSuperview];
    //[btn_Back removeFromSuperview];
    
}


@end

